package com.itheima;

import org.junit.Test;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class Tpoic560 {


    public int subarraySum(int[] nums, int k) {

        int count = 0;
        for(int start = 0; start < nums.length; start++) {
            int sum = 0;
            for(int end = start; end >= 0; end--) {
                sum += nums[end];
                if(sum == k)
                    count++;
            }
        }
//        System.out.println(count);
        return count;
    }

    public int subarraySum1(int[] nums, int k) {

        int count = 0;
        int pre = 0; //pre[i - 1] 前i-1数组的和

        Map<Integer, Integer> map = new HashMap<>();
        map.put(0, 1);
        for(int i = 0; i < nums.length; i++) {
            pre += nums[i];
            if(map.containsKey(pre - k)) {
                count++;
            }
            map.put(pre, map.getOrDefault(pre, 0) + 1);
        }

        System.out.println(count);
        return count;
    }

    @Test
    public void test() {
        subarraySum1(new int[]{1,-1,0}, 0);
    }
}
